package com.integral.biz.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.integral.biz.IBalanceBiz;
import com.integral.biz.IDeclarationBiz;
import com.integral.biz.IOrderBiz;
import com.integral.biz.IUserBiz;
import com.integral.biz.IUserTypeBiz;
import com.integral.constant.OrderConstant;
import com.integral.constant.UserTypeCode;
import com.integral.entity.Balance;
import com.integral.entity.User;
import com.integral.entity.UserInfo;
import com.integral.entity.UserType;
import com.integral.service.UserService;
import com.integral.service.UserTypeService;
import com.integral.vo.DeclarationVo;
import com.integral.vo.OrderVo;
import com.integral.vo.UserVo;

/**
 * @Description: 用户表BIZ实现类
 * @author zhaofan
 * @date 2018年05月08日 上午01:01:17
 */
@Service("userBiz")
public class UserBiz implements IUserBiz {
	protected final Log logger = LogFactory.getLog(getClass());
	/**
	 * 注入用户表Service
	 */
	@Resource
	private UserService userService;
	@Resource
	private UserTypeService userTypeService;
	//注入用户类型
	@Resource
	private IUserTypeBiz userTypeBiz;
	//注入用户余额
	@Resource
	private IBalanceBiz balanceBiz;
	//注入报单
	@Resource
	private IDeclarationBiz declarationBiz;
	//注入订单
	@Resource
	private IOrderBiz orderBiz;
	
	/**
	 * @Description: 新增用户表
	 * @param user
	 * @return 受影响行数
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:01:17
	 */
	public int addUser(User user) {
		return userService.addUser(user);
	}
	
	/**
	 * @Description: 修改用户表
	 * @param user 用户表
	 * @return 受影响行数
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:01:17
	 */
	public int updateUser(User user) {
		return userService.updateById(user);
	}
	
	/**
	 * @Description: 删除用户表
	 * @param id 主键
	 * @return 受影响行数
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:01:17
	 */
	public int deleteUser(Long id) {
		return userService.deleteById(id);
	}
	
	/**
	 * @Description: 根据Code查询用户表
	 * @param id 主键
	 * @return 用户表
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:01:17
	 */
	public User findByCode(String userCode) {
		return userService.findByCode(userCode);
	}
	
	/**
	 * 用户列表查询
	 * @param userVo
	 * @return
	 * @author zhaofan
	 * @date 2018年05月11日 上午02:14:36
	 */
	public List<UserVo> findUser(UserVo userVo){
		List<UserVo> list = userService.findUser(userVo);
		for (UserVo user : list) {
			codeTransform(user);
			//获取用户余额
			Balance balance = balanceBiz.findByUserCode(user.getUserCode());
			if(null != balance){
				user.setBalance(balance.getUserMoney());
			}
		}
		return list;
	}
	
	/**
	 * 编码转换
	 * @param user
	 */
	public void codeTransform(UserVo user){
		//上级用户编码转换
		if(!StringUtils.isEmpty(user.getUserSuperiorCode())){
			User u = userService.findByCode(user.getUserSuperiorCode());
			if(null != u){
				user.setUserSuperiorCodeName(u.getUserName());
				if(!StringUtils.isEmpty(u.getUserSuperiorCode())){
					User uTwo = userService.findByCode(u.getUserSuperiorCode());
					if(null != uTwo){
						user.setUserSuperiorCodeNameTwo(uTwo.getUserName());
						if(!StringUtils.isEmpty(uTwo.getUserSuperiorCode())){
							User uThree = userService.findByCode(uTwo.getUserSuperiorCode());
							if(null != uThree){
								user.setUserSuperiorCodeNameThree(uThree.getUserName());
							}
						}
					}
				}
				
			}
		}
		//用户类别编码转换
		if(!StringUtils.isEmpty(user.getUserTypeCode())){
			UserType userType = userTypeService.findByCode(user.getUserTypeCode());
			if(null != userType){
				user.setUserTypeCodeName(userType.getUserTypeName());
			}
		}
	}
	
	/**
	 * 获取总记录数
	 * @param userVo
	 * @return
	 */
	public Long findUserCount(UserVo userVo){
		return userService.findUserCount(userVo);
	}
	/**
	 * 根据用户唯一标识查询用户
	 * @param userOpenid
	 * @return
	 */
	public UserVo findByUserOpenid(String userOpenid){
		UserVo userVo = userService.findByUserOpenid(userOpenid);
		if(null != userVo){
			UserType userType = userTypeService.findByCode(userVo.getUserTypeCode());
			userVo.setUserTypeCodeName(userType.getUserTypeName());
			//查询用户余额
			Balance balance = balanceBiz.findByUserCode(userVo.getUserCode());
			if(null != balance){
				userVo.setBalance(balance.getUserMoney());
			}
			//查询上级用户名称
			if(!StringUtils.isEmpty(userVo.getUserSuperiorCode())){
				User u = this.findByCode(userVo.getUserSuperiorCode());
				if(null != u){
					userVo.setUserSuperiorCodeName(u.getUserName());
				}
			}
			//查询累计盈利(查询订单)
			findProfit(userVo);
			//查询用户报单（获取审核中，成功报单，失败报单）
			findDeclarationByUser(userVo);
			//查询用户累计提现
			findWithdraw(userVo);
			
			//查询下级用户
			UserVo user = new UserVo();
			user.setUserSuperiorCode(userVo.getUserCode());
			List<UserVo> userList = userService.findUser(user);
			for (UserVo userVo2 : userList) {
				//用户类别编码转换
				if(!StringUtils.isEmpty(userVo2.getUserTypeCode())){
					UserType usertype = userTypeService.findByCode(userVo2.getUserTypeCode());
					if(null != usertype){
						userVo2.setUserTypeCodeName(usertype.getUserTypeName());
					}
				}
			}
			userVo.setSubordinate(userList);
		}
		
		return userVo;
	}
	/**
	 * 查询累计提现
	 */
	private void findWithdraw(UserVo userVo){
		BigDecimal sumMoney = BigDecimal.ZERO;
		OrderVo orderVo = new OrderVo();
		orderVo.setUserCode(userVo.getUserCode());
		List<OrderVo> list = orderBiz.findOrder(orderVo);
		for (OrderVo orderVo2 : list) {
			sumMoney.add(orderVo2.getExchangeMoney());
		}
		userVo.setWithdrawSum(sumMoney);
	}
	/**
	 * 查询累计盈利(查询订单)
	 */
	private void findProfit(UserVo userVo){
		if(StringUtils.isEmpty(userVo.getUserCode())){
			logger.error("获取不到用户编码："+JSON.toJSONString(userVo));
			return;
		}
		//盈利明细-积分兑换
		List<OrderVo> profitIntegral = new ArrayList<>();
		//赢利明细-下级返利
		List<OrderVo> profitRelation = new ArrayList<>();
		OrderVo orderVo = new OrderVo();
		orderVo.setStart(null);
		orderVo.setPageSize(null);
		orderVo.setUserCode(userVo.getUserCode());
		List<OrderVo> list = orderBiz.findOrder(orderVo);
		//累计赢利
		BigDecimal profit = new BigDecimal(0);
		for (OrderVo orderVo2 : list) {
			//盈利明细-积分兑换
			if(orderVo2.getOrderType() == OrderConstant.ORDER_TYPE_INTEGRAL){
				profitIntegral.add(orderVo2);
				//累计赢利
				profit = profit.add(orderVo2.getExchangeMoney());
			}
			//赢利明细-下级返利
			if(orderVo2.getOrderType() == OrderConstant.ORDER_TYPE_RELATION){
				profitRelation.add(orderVo2);
				//累计赢利
				profit = profit.add(orderVo2.getExchangeMoney());
			}
		}
		//累计盈利
		userVo.setProfit(profit);
		//盈利明细-积分兑换
		userVo.setProfitIntegral(profitIntegral);
		//赢利明细-下级返利
		userVo.setProfitRelation(profitRelation);
	}
	/**
	 * 查询用户报单（获取审核中，成功报单，失败报单）
	 * @param userVo
	 */
	private void findDeclarationByUser(UserVo userVo){
		if(StringUtils.isEmpty(userVo.getUserOpenid())){
			logger.error("获取不到用户唯一标识："+JSON.toJSONString(userVo));
			return;
		}
		//成功报单
		List<DeclarationVo> declarationSuccess = new ArrayList<>();
		//失败报单
		List<DeclarationVo> declarationFail = new ArrayList<>();
		//审核中报单
		List<DeclarationVo> declarationLoding = new ArrayList<>();
		//封装查询参数
		DeclarationVo declarationVo = new DeclarationVo();
		declarationVo.setStart(null);
		declarationVo.setPageSize(null);
		declarationVo.setUserOpenid(userVo.getUserOpenid());
		List<DeclarationVo> list = declarationBiz.findDeclaration(declarationVo);
		for (DeclarationVo declarationVo2 : list) {
			if(declarationVo2.getStatus() == 1){
				declarationSuccess.add(declarationVo2);
			}
			if(declarationVo2.getStatus() == 2){
				declarationFail.add(declarationVo2);
			}
			if(declarationVo2.getStatus() == 0){
				declarationLoding.add(declarationVo2);
			}
		}
		userVo.setDeclarationSuccess(declarationSuccess);
		userVo.setDeclarationFail(declarationFail);
		userVo.setDeclarationLoding(declarationLoding);
		
	}
	/**
	 * 设置用户
	 * 若用户存在，则返回用户信息。
	 * 若用户不存在，则新增用户(若携带上级用户编码，则设置上级用户)
	 * @param userOpenid
	 */
	public User findUserAddUser(String userOpenid,String userName,String userSuperiorCode){
		//校验用户是否存在
		UserVo user = userService.findByUserOpenid(userOpenid);
		if(null == user){
			//用户不存在，则新增用户
			User insrtUser = new User();
			insrtUser.setUserName(userName);
			insrtUser.setUserOpenid(userOpenid);
			Double randomNum = Math.random()*9;
			String uCode = randomNum.toString();
			uCode = uCode.substring(uCode.length()-9, uCode.length());
			insrtUser.setUserCode("WX"+uCode);
			insrtUser.setUserTypeCode(UserTypeCode.USER_CODE);
			//上级用户编码
			if(!StringUtils.isEmpty(userSuperiorCode) && !"undefined".equals(userSuperiorCode)){
				insrtUser.setUserSuperiorCode(userSuperiorCode);
			}
			this.addUser(insrtUser);
			
			//查询用户奖励
			UserType userType = userTypeBiz.findByCode(UserTypeCode.USER_CODE);
			//创建用户余额
			Balance balance = new Balance();
			balance.setUserCode(insrtUser.getUserCode());
			balance.setUserMoney(userType.getUserAward());
			balanceBiz.addBalance(balance);
			
			return insrtUser;
		}
		User requestUser = new User();
		requestUser.setUserCode(user.getUserCode());
		requestUser.setUserOpenid(user.getUserOpenid());
		return requestUser;
	}
	
	/**
	 * 根据用户唯一openid修改用户类型（查询用户奖励，并修改余额）
	 * @param user
	 * @return
	 */
	public int updateByUserType(User user){
		
		if(!StringUtils.isEmpty(user.getUserTypeCode())){
			UserType userType = userTypeService.findByCode(user.getUserTypeCode());
			if(null != userType){
				//查询用户，获取用户编码
				UserVo userVo = userService.findByUserOpenid(user.getUserOpenid());
				//查询用户余额
				Balance balance = balanceBiz.findByUserCode(userVo.getUserCode());
				balance.setUserMoney(balance.getUserMoney().add(userType.getUserAward()));
				//修改用户余额
				balanceBiz.updateBalance(balance);
			}
		}
		return userService.updateByUserType(user);
	}
	
	/**
	 * 根据帐号密码，查询登录用户
	 * @param userInfo
	 * @return
	 */
	@Override
	public UserInfo findUserInfo(UserInfo userInfo){
		return userService.findUserInfo(userInfo);
	}
	
	/**
	 * 根据用户编码修改用户手机号
	 * @param user
	 * @return
	 */
	public int updateByPhoneNum(User user){
		return userService.updateByPhoneNum(user);
	}
}